<?php

if (!function_exists('cache')) {	
	function cache($key,$value=''){
		
		$cache = new \EasySwoole\FastCache\Cache();
		//设置
		if(!empty($key)&&!empty($value)){
			$cache->set($key,$value);
		}		
		if ('' === $value) {
            // 获取缓存
            return $cache->get($key);
        }
		if (is_null($value)) {
            // 删除缓存
            $cache->set($key,null);
        }
	}
}

//取得config表中键值数据
function DbConfig($key){
	
	if(!$db_config=cache('db_config')){
		
		$model=new \App\Model\Admin\Config();
		
		$db_config=$model->get_db_config();
		
		cache('db_config',$db_config);
	}
	if(!isset($db_config[$key])){
		return null;
	}
	return $db_config[$key];
}

function osc_service($service_name)
{
	$class = '\\App\\Server\\' . ucwords($service_name);	
	
	if (class_exists($class)) {
		   return new $class();
	} else {
		throw new \Exception('class not exists:' . $class);		
	}
}
function osc_model($module_name,$model_name)
{
	$class = '\\App\\Model\\'.ucwords($module_name).'\\'. ucwords($model_name);	
	
	if (class_exists($class)) {
		   return new $class();
	} else {
			throw new \Exception('class not exists:' . $class);	
	}
}
function osc_tools($name,$module=null)
{	
	if($module){
		$class = '\\App\\Utility\\'.ucwords($module).'\\'.ucwords($name);	
	}else{
		$class = '\\App\\Utility\\'.ucwords($name);	
	}
	
	if (class_exists($class)) {
		   return new $class();
	} else {
			throw new \Exception('class not exists:' . $class);	
	}
}
function osc_validate($module_name,$name)
{
	$class = '\\App\\Validate\\'.ucwords($module_name).'\\'. ucwords($name);	
	
	if (class_exists($class)) {
		   return new $class();
	} else {
			throw new \Exception('class not exists:' . $class);	
	}
}
if (!function_exists('url')) {	
	function url($url, $vars = []){		
		return $url.osc_tools('url')->make_url_param($vars);		
	}
}
//输入数据过滤
function array_map_recursive($filter, $data)
{
    $result = array();
    foreach ($data as $key => $val) {
        $result[$key] = is_array($val)
        ? array_map_recursive($filter, $val)
        : call_user_func($filter, $val);
    }
    return $result;
}
//输入数据过滤
function think_filter(&$value)
{
    // TODO 其他安全过滤

    // 过滤查询特殊字符
    if (preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT LIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOT EXISTS|NOTEXISTS|EXISTS|NOT NULL|NOTNULL|NULL|BETWEEN TIME|NOT BETWEEN TIME|NOTBETWEEN TIME|NOTIN|NOT IN|IN)$/i', $value)) {
        $value .= ' ';
    }
}
//输入数据过滤
function sys_filter($data){

    $filters = 'htmlspecialchars';
    if ($filters) {
        if (is_string($filters)) {
            $filters = explode(',', $filters);
        }
        foreach ($filters as $filter) {
            $data = array_map_recursive($filter, $data); // 参数过滤
        }
    }
	is_array($data) && array_walk_recursive($data, 'think_filter');

    return $data;
}